# -*- coding: utf-8 -*-



def extract_record(player, s):
  """
  Record at FIFA Tournaments
  """
  player['association'] = s.xpath('./div[@class="title"]/h4/a/text()').extract()[0].strip()
  player['name'] = s.xpath('./div[@class="title"]/h1/text()').extract()[0].strip()
  _s = s.xpath('./div[@class="title"]/h4[@class="birthdate"]/text()')
  if len(_s) > 0:
    player['birthdate'] = _s.extract()[0].replace('(','').replace(')','').strip()
  else:
    player['birthdate'] = ''






def extract_match(name, player, s):
  record = []
  """
  extract match information from table
  """

  # skip it when table content is 'No data available'
  _s1 = s.xpath('./table/tbody/tr/td[1]/@colspan')
  if len(_s1) > 0 and '7' == _s1.extract()[0].strip():
    return




  sel = s.xpath('./table/tbody/tr')
  for row in sel:
    match = dict()
    match['edition'] = row.xpath('./td[1]/text()').extract()[0].strip()
    match['venue'] = row.xpath('./td[2]/text()').extract()[0].strip()
    match['date'] = row.xpath('./td[3]/text()').extract()[0].strip()

    selht = row.xpath('./td[4]/a[2]')
    if len(selht) == 0:
      match['hometeam'] = row.xpath('./td[4]/text()').extract()[0].strip()
    else:
      match['hometeam'] = selht.xpath('./text()').extract()[0].strip()

    selres = row.xpath('./td[5]/a')
    if len(selres) == 0:
      match['page'] = ''
      match['result'] = row.xpath('./td[5]/text()').extract()[0].strip()
    else:
      match['page'] = row.xpath('./td[5]/a/@href').extract()[0].strip()
      match['result'] = row.xpath('./td[5]/a/text()').extract()[0].strip()


    selat = row.xpath('./td[6]/a[1]')
    if len(selat) == 0:
      match['awayteam'] = row.xpath('./td[6]/text()').extract()[0].strip()
    else:
      match['awayteam'] = selat.xpath('./text()').extract()[0].strip()

    match['stage'] = row.xpath('./td[7]/text()').extract()[0].strip()
    
    record.append(match)

  player['match_records'][name] = record


def extract_cfd_cup(player, s):
  """
  FIFA Confederations Cup
  """
  extract_match('cfd_cup', player, s)


def extract_wc_qualifiers(player, s):
  """
  FIFA World Cup Qualifiers
  """
  extract_match('wc_qualifiers', player, s)

def extract_wc(player, s):
  """
  FIFA World Cup
  """
  extract_match('wc', player, s)

def extract_olympic(player, s):
  """
  Men's Olympic Football Tournament
  """
  extract_match('olympic', player, s)


def extract_club_cup(player, s):
  """
  FIFA Club World Cup
  """
  extract_match('club_cup', player, s)

def extract_u20(player, s):
  """
  FIFA U-20 World Cup
  """
  extract_match('u20', player, s)

def extract_u17(player, s):
  """
  FIFA U-17 World Cup
  """
  extract_match('u17', player, s)